<?php
/**
 * Created by dailinlin.
 * Date: 2019/12/2 17:12
 * for:
 */


namespace app\common\controller;


use app\admin\model\Area;
use app\admin\model\Hospital;
use app\admin\model\School;
use app\admin\model\Student as StudentModel;
use app\common\model\Ent;
use app\common\model\Eyes;
use app\common\model\Fluoroscopy;
use app\common\model\Liver;
use app\common\model\Medicine;
use app\common\model\Stomatology;
use app\common\model\Surgery;
use auth\Auth;
use CodeItNow\BarcodeBundle\Utils\BarcodeGenerator;
use think\Db;
use think\facade\Config;
use think\facade\View;
use think\helper\Str;
use think\facade\Request;

class BaseAdmin extends Base
{

    protected $auth_uid;    //后台管理员登录id
    protected $wxappid ;    //店铺编号

    public function initialize(){
        $this->checkAuth();
        $this->get_wxappid(); // 获取当前登录管理员所属商户标识
    }


    /**
     * 权限登录检查
     * @param null $action
     * @param null $controller
     * @param null $module
     * @param array $route
     * @throws \Exception
     */

    protected function checkAuth($action = null,$controller = null,$module = null,array $route = []){
        if($module === null) $module = app('http')->getName();
        if($controller === null) $controller = $this->request->controller();
        if($action === null) $action = $this->request->action();

        //拼接路由
        $url = Str::lower($module.'/'.$controller.'/'.$action);
      //  print_r($url);exit;
        //权限监测
        $auth = Auth::instance();
        $config = Config::get('login_admin');

        //无需认证模块
        $modules = explode(',',$config['not_auth_module']);
        $check = in_array(Str::lower($module.'/'.$controller),$modules);

        //是否登录否则人让用户登录
        $this->auth_uid = session($config['auth_uid']);
        if (!$this->auth_uid&&!$check){
            $this->redirect(url($config['user_auth_gateway']));
        }

        if(!$check&&!$auth->check($url, $this->auth_uid)){
            if($this->request->isAjax()){
                $this->error('对不起您没有该操作权限!');
            }else{
                echo $this->fetch('template@layout/access_denied');die;
            }
        }

        //后台操作日志
        admin_log($this->auth_uid?:0);
    }

    /**
     * 获取当前登录管理员所属商户标识
    */

    protected function get_wxappid(){
        $this->wxappid = session('wxapp_id');
      // return $wxapp_id;
    }
    /**
     * 是否登录否则跳转登录页面
     */
    protected function checkLogin(){
        $config = Config::get('login_admin');
        $auth_uid = session($config['auth_uid']);
        if (!$auth_uid){
           $this->redirect(url($config['user_auth_gateway']));
        }
    }


    /**
     * 模板变量赋值
     * @param $name
     * @param null $value
     */
    protected function assign($name, $value = null){
        View::assign($name,$value);
    }

    /**
     * 解析和获取模板内容 用于输出
     * @param string $template
     * @param array $vars
     * @return string
     * @throws \Exception
     */
    protected function fetch(string $template = '', array $vars = []){
        return View::fetch($template, $vars);
    }


    /**
     * 返回表格数据
     * @param $data
     * @param $total
     * @return array
     */
    protected function tableJson($data, $total)
    {
        $json = [
            'code' => 0,
            'msg' => '',
            'data' => $data,
        ];
        if ($total) {
            $json = array_merge($json, ['count' => $total]);
        }
        return $json;
    }


    /**
     * 配合withSearch搜索器使用
     * @param $data
     * @return array
     */
    protected function searchFields($data){
        unset($data['limit']);
        $data = array_keys($data);
        return $data;
    }

    /**
     * 配合withSearch搜索器使用
     * @param $data
     * @return array
     */
    protected function searchData($data){
        unset($data['limit']);
        return $data;
    }

    /**
     * 递归  列
     * @param $array
     * @param $id
     * @return array
     */
    public function getTreeOrder($array,$id = 0,$level = 0){
        static $arr = [];
        foreach($array as $k=>$v){
            if($v['parent_id'] == $id){
                $v['level'] = $level;
                $str ="";
                for ($i=0;$i<$level;$i++){
                    $str = $str."|----";
                }
                $v['levelName'] = $str.''.$v['name'];
                $arr[] = $v;
                unset($array[$k]);
                $this->getTreeOrder($array,$v['id'],$level+1);
            }
        }
      //  print_r($arr);exit;
        return $arr;
    }


    /**
     * 图片上传(ajax)
     * @return \think\Response|void
     * @throws \Exception
     */
    public function uploadImg(){
        $files = request()->file();
        $type = request()->get('uptype');
        // print_r($type);exit;
        if(empty($type)){
            $type = 'images';
        }
            validate(['image'=>'filesize:10240|fileExt:jpg,png,jpeg,gif'])
                ->check($files);
            $savenames = [];
            foreach($files as $file) {
                $savenames[] = \think\facade\Filesystem::disk('public')->putFile( $type, $file);
            }
            $getSaveName=str_replace("\\","/",$savenames);//把反斜杠(\)替换成斜杠(/) 因为在windows下上传路是反斜杠径20180914\a6587063b2abbda94
            $getSaveName = implode('|',$getSaveName);
           // print_r($getSaveName);exit;
        $data=[];
        if($getSaveName) {
            $data = [
                'img_url' => "/storage/" . $getSaveName,
                'src' => 'http://' . $_SERVER['HTTP_HOST'] . "/storage/" . $getSaveName,
                'title' => '图片',
            ];
        }
            return $data;
    }
    /**
     * 图片连接处理
     * 相对路径 转为绝对路径
     */
    public  function imagesUrl($image_url){
        if(empty($image_url)){
            return $image_url;
        }
        $preg = "/^http(s)?:\\/\\/.+/";
        if(preg_match($preg,$image_url))
        {
            return $image_url;
        }else
        {
            $request = Request::instance();
            $domain = $request->domain();

            return $domain.$image_url;
        }
    }
}